﻿using Dyd.BaseService.ConfigManager.Domain;
using Dyd.BaseService.ConfigManager.Domain.Dal;
using Dyd.BaseService.ConfigManager.Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using XXF.Db;
using Dyd.BaseService.ConfigManager.Web.Tools;
using XXF.Extensions;

namespace Dyd.BaseService.ConfigManager.Web.Controllers
{
    [Authorize]
    public class ProjectController : Controller
    {
        private tb_log_dal logDal = new tb_log_dal();
        private tb_project_dal projectDal = new tb_project_dal();
        private tb_category_dal categoryDal = new tb_category_dal();
        private tb_config_dal configDal = new tb_config_dal();
        #region 列表
        public ActionResult ProjectIndex(int categoryid = 0, string name = "", string remark = "", int pageIndex = 1, int pageSize = 20)
        {
            ViewBag.Name = name;
            ViewBag.Remark = remark;
            int count = 0;
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();

                List<SelectListItem> ddlList = new List<SelectListItem>();
                ddlList.Add(new SelectListItem { Text = "全部", Value = " " });

                var cateList = categoryDal.GetList(conn);
                foreach (var item in cateList)
                {
                    var selected = categoryid == item.id;
                    ddlList.Add(new SelectListItem { Text = item.name, Value = item.id.ToString(), Selected = selected });
                }
                ViewBag.Category = ddlList;

                IList<tb_project_model> list = projectDal.GetPageList(conn, categoryid, name, remark, pageSize, pageIndex, ref count);

                foreach (var item in list)
                {
                    var ids = item.categoryids.Split(',').ToList();
                    //ids.Reverse();
                    foreach (var idItem in ids)
                    {
                        if (!string.IsNullOrWhiteSpace(idItem))
                        {
                            var id = Convert.ToInt32(idItem);
                            item.categorynames += cateList.FirstOrDefault(s => s.id == id).name + "->";
                        }
                    }
                    item.categorynames = item.categorynames.NullToEmpty();
                    if (item.categorynames.Length > 0)
                    {
                        item.categorynames = item.categorynames.Substring(0, item.categorynames.Length - 2);
                    }
                }

                PagedList<tb_project_model> pageList = new PagedList<tb_project_model>(list, pageIndex, pageSize, count);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_ProjectIndex", pageList);
                }
                else
                {
                    return View(pageList);
                }
            }
        }

        #endregion

        #region 新增
        public ActionResult ProjectAdd()
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                int count = 0;
                var list = categoryDal.GetPageList(conn, "", "", 100, 1, ref count);
                ViewBag.CategoryList = list;
                return View();
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult ProjectAdd(tb_project_model model)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    conn.BeginTransaction();
                    model.createtime = conn.GetServerDate();
                    model.lastheartbeattime = conn.GetServerDate();
                    model.projectname = model.projectname.Trim();
                    var id = projectDal.Add(conn, model);
                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = -1,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                        ProjectName = model.projectname
                    });
                    conn.Commit();
                    logDal.Add(conn, string.Format("{0}|Id:{1}|Name:{2}", "添加项目", id, model.projectname), model.projectname);
                    return Json(new OperateResults { Flag = true, Message = "添加成功！" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception exp)
                {
                    conn.Rollback();
                    return Json(new OperateResults { Flag = false, Message = exp.Message }, JsonRequestBehavior.AllowGet);
                }
            }
        }
        #endregion

        #region 修改
        public ActionResult ProjectEdit(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                int count = 0;
                var list = categoryDal.GetPageList(conn, "", "", 100, 1, ref count);
                var model = projectDal.Get(conn, id);
                ViewBag.CategoryList = list;
                var ids = string.Empty;
                if (model != null && !string.IsNullOrWhiteSpace(model.categoryids))
                {
                    var start = model.categoryids.IndexOf(",");
                    var end = model.categoryids.LastIndexOf(",");
                    ids = model.categoryids.Trim(',');
                    var orderList = new List<tb_category_model>();
                    if (!string.IsNullOrWhiteSpace(ids))
                    {
                        var unOrderList = categoryDal.GetListByIds(conn, ids);
                        foreach (var item in ids.Split(','))
                        {
                            var cId = Convert.ToInt32(item);
                            orderList.Add(unOrderList.FirstOrDefault(s => s.id == cId));
                        }
                    }
                    ViewBag.ProjectCategory = orderList;
                }
                return View(model);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ProjectEdit(tb_project_model model)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    conn.BeginTransaction();
                    var modelsource = projectDal.Get(conn, model.id);
                    model.projectname = model.projectname.Trim();
                    model.lastheartbeattime = conn.GetServerDate();
                    projectDal.Edit(conn, model);
                    if (modelsource.projectname != model.projectname || modelsource.categoryids != model.categoryids)
                    {
                        RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                        {
                            CategoryID = -1,
                            CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                            ProjectName = modelsource.projectname
                        });
                        if (modelsource.projectname != model.projectname)
                        {
                            RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                            {
                                CategoryID = -1,
                                CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                                ProjectName = model.projectname
                            });
                        }
                    }
                    conn.Commit();
                    logDal.Add(conn, string.Format("{0}|Id:{1}|Name:{2}", "修改项目", model.id, model.projectname), model.projectname);
                    return Json(new OperateResults { Flag = true, Message = "修改成功！" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception exp)
                {
                    conn.Rollback();
                    return Json(new OperateResults { Flag = false, Message = exp.Message }, JsonRequestBehavior.AllowGet);
                }
            }
        }
        #endregion

        #region 详情
        public ActionResult ProjectDetails(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                IList<tb_config_model> allConfig = new List<tb_config_model>();

                conn.Open();
                int count = 0;
                var list = categoryDal.GetPageList(conn, "", "", 100, 1, ref count);
                var model = projectDal.Get(conn, id);
                if (model != null)
                {
                    var ids = model.categoryids.Split(',').ToList();
                    ids.Reverse();
                    foreach (var item in ids)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            var category = categoryDal.Get(conn, Convert.ToInt32(item));
                            var configList = configDal.GetByCategoryId(conn, category.id);
                            foreach (var config in configList)
                            {
                                if (allConfig.Any(s => s.configkey == config.configkey))
                                {
                                    config.InheritanceFlag = true;
                                }
                                category.tb_config_model.Add(config);
                                allConfig.Add(config);
                            }
                            model.tb_category_model.Add(category);
                        }
                    }
                }
                return View(model);
            }
        }

        #endregion

        #region 删除
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult ProjectDel(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    var model = projectDal.Get(conn, id);
                    projectDal.Delete(conn, id);

                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = -1,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                        ProjectName = model.projectname
                    });
                    logDal.Add(conn, string.Format("{0}|Id:{1}|Name:{2}", "删除项目", model.id, model.projectname), model.projectname);
                    return Json(new OperateResults { Flag = true, Message = "删除成功！" });
                }
                catch (Exception exp)
                {
                    return Json(new OperateResults { Flag = false, Message = exp.Message });
                }
            }
        }

        #endregion

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult ClientReloadConfig(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    var model = projectDal.Get(conn, id);

                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = -1,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                        ProjectName = model.projectname
                    });
                    logDal.Add(conn, string.Format("{0}|Id:{1}|Name:{2}", "已经发送客户端重启通知", model.id, model.projectname), model.projectname);
                    return Json(new OperateResults { Flag = true, Message = "已经发送客户端重启通知！" });
                }
                catch (Exception exp)
                {
                    return Json(new OperateResults { Flag = false, Message = exp.Message });
                }
            }
        }
    }
}
